package com.smart.community.commons.test;

import com.smart.community.commons.aspect.FeignCallMonitorAspect;
import com.smart.community.commons.service.ServiceHealthMonitor;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 监控功能验证类
 * 
 * 验证监控功能，包括调用统计和健康检查
 * 
 * @author Wu.Liang
 * @version 2.0.0
 * @since 2025-08-28
 */
@Slf4j
public class MonitorValidation {
    
    /**
     * 验证监控功能
     */
    public static void validateMonitorFunction() {
        log.info("开始验证监控功能...");
        
        // 验证调用统计功能
        validateCallStatistics();
        
        // 验证健康检查功能
        validateHealthCheck();
        
        log.info("监控功能验证完成！");
    }
    
    /**
     * 验证调用统计功能
     */
    private static void validateCallStatistics() {
        log.info("验证调用统计功能...");
        
        // 模拟调用统计
        simulateCallStatistics();
        
        // 验证统计结果
        validateCallStatisticsResults();
        
        log.info("✅ 调用统计功能验证通过");
    }
    
    /**
     * 模拟调用统计
     */
    private static void simulateCallStatistics() {
        log.info("模拟调用统计...");
        
        // 获取统计实例
        ConcurrentHashMap<String, FeignCallMonitorAspect.CallStatistics> statisticsMap = 
            FeignCallMonitorAspect.getAllCallStatistics();
        
        // 模拟成功调用
        simulateSuccessfulCall("TestService.testMethod1");
        simulateSuccessfulCall("TestService.testMethod1");
        simulateSuccessfulCall("TestService.testMethod2");
        
        // 模拟失败调用
        simulateFailedCall("TestService.testMethod1");
        simulateFailedCall("TestService.testMethod3");
        
        log.info("模拟调用统计完成，当前统计项数: {}", statisticsMap.size());
    }
    
    /**
     * 模拟成功调用
     */
    private static void simulateSuccessfulCall(String serviceKey) {
        FeignCallMonitorAspect.CallStatistics stats = 
            FeignCallMonitorAspect.getAllCallStatistics().computeIfAbsent(serviceKey, k -> new FeignCallMonitorAspect.CallStatistics());
        
        // 模拟100ms的调用时间
        stats.recordSuccess(100);
        
        log.debug("模拟成功调用: {}, 总调用: {}, 成功: {}, 失败: {}, 成功率: {:.2f}%", 
                serviceKey, stats.getTotalCalls(), stats.getSuccessCalls(), 
                stats.getFailureCalls(), stats.getSuccessRate() * 100);
    }
    
    /**
     * 模拟失败调用
     */
    private static void simulateFailedCall(String serviceKey) {
        FeignCallMonitorAspect.CallStatistics stats = 
            FeignCallMonitorAspect.getAllCallStatistics().computeIfAbsent(serviceKey, k -> new FeignCallMonitorAspect.CallStatistics());
        
        // 模拟50ms的调用时间
        stats.recordFailure(50);
        
        log.debug("模拟失败调用: {}, 总调用: {}, 成功: {}, 失败: {}, 成功率: {:.2f}%", 
                serviceKey, stats.getTotalCalls(), stats.getSuccessCalls(), 
                stats.getFailureCalls(), stats.getSuccessRate() * 100);
    }
    
    /**
     * 验证调用统计结果
     */
    private static void validateCallStatisticsResults() {
        log.info("验证调用统计结果...");
        
        ConcurrentHashMap<String, FeignCallMonitorAspect.CallStatistics> statisticsMap = 
            FeignCallMonitorAspect.getAllCallStatistics();
        
        // 验证TestService.testMethod1的统计结果
        FeignCallMonitorAspect.CallStatistics stats1 = statisticsMap.get("TestService.testMethod1");
        if (stats1 != null) {
            log.info("TestService.testMethod1统计结果:");
            log.info("  总调用次数: {}", stats1.getTotalCalls());
            log.info("  成功调用次数: {}", stats1.getSuccessCalls());
            log.info("  失败调用次数: {}", stats1.getFailureCalls());
            log.info("  成功率: {:.2f}%", stats1.getSuccessRate() * 100);
            log.info("  平均响应时间: {:.2f}ms", stats1.getAverageDuration());
            
            // 验证预期结果：3次调用，2次成功，1次失败
            if (stats1.getTotalCalls() == 3 && stats1.getSuccessCalls() == 2 && stats1.getFailureCalls() == 1) {
                log.info("✅ TestService.testMethod1统计结果验证通过");
            } else {
                log.error("❌ TestService.testMethod1统计结果验证失败");
            }
        }
        
        // 验证TestService.testMethod2的统计结果
        FeignCallMonitorAspect.CallStatistics stats2 = statisticsMap.get("TestService.testMethod2");
        if (stats2 != null) {
            log.info("TestService.testMethod2统计结果:");
            log.info("  总调用次数: {}", stats2.getTotalCalls());
            log.info("  成功调用次数: {}", stats2.getSuccessCalls());
            log.info("  失败调用次数: {}", stats2.getFailureCalls());
            log.info("  成功率: {:.2f}%", stats2.getSuccessRate() * 100);
            
            // 验证预期结果：1次调用，1次成功，0次失败
            if (stats2.getTotalCalls() == 1 && stats2.getSuccessCalls() == 1 && stats2.getFailureCalls() == 0) {
                log.info("✅ TestService.testMethod2统计结果验证通过");
            } else {
                log.error("❌ TestService.testMethod2统计结果验证失败");
            }
        }
        
        // 验证TestService.testMethod3的统计结果
        FeignCallMonitorAspect.CallStatistics stats3 = statisticsMap.get("TestService.testMethod3");
        if (stats3 != null) {
            log.info("TestService.testMethod3统计结果:");
            log.info("  总调用次数: {}", stats3.getTotalCalls());
            log.info("  成功调用次数: {}", stats3.getSuccessCalls());
            log.info("  失败调用次数: {}", stats3.getFailureCalls());
            log.info("  成功率: {:.2f}%", stats3.getSuccessRate() * 100);
            
            // 验证预期结果：1次调用，0次成功，1次失败
            if (stats3.getTotalCalls() == 1 && stats3.getSuccessCalls() == 0 && stats3.getFailureCalls() == 1) {
                log.info("✅ TestService.testMethod3统计结果验证通过");
            } else {
                log.error("❌ TestService.testMethod3统计结果验证失败");
            }
        }
    }
    
    /**
     * 验证健康检查功能
     */
    private static void validateHealthCheck() {
        log.info("验证健康检查功能...");
        
        // 创建健康监控服务实例
        ServiceHealthMonitor healthMonitor = new ServiceHealthMonitor();
        
        // 模拟健康检查
        simulateHealthCheck(healthMonitor);
        
        // 验证健康检查结果
        validateHealthCheckResults(healthMonitor);
        
        log.info("✅ 健康检查功能验证通过");
    }
    
    /**
     * 模拟健康检查
     */
    private static void simulateHealthCheck(ServiceHealthMonitor healthMonitor) {
        log.info("模拟健康检查...");
        
        // 手动触发健康检查
        healthMonitor.checkServiceHealth();
        
        log.info("健康检查模拟完成");
    }
    
    /**
     * 验证健康检查结果
     */
    private static void validateHealthCheckResults(ServiceHealthMonitor healthMonitor) {
        log.info("验证健康检查结果...");
        
        Map<String, ServiceHealthMonitor.HealthStatus> healthStatusMap = healthMonitor.getAllHealthStatus();
        
        // 验证停车服务健康状态
        ServiceHealthMonitor.HealthStatus parkingStatus = healthStatusMap.get("停车服务");
        if (parkingStatus != null) {
            log.info("停车服务健康状态:");
            log.info("  服务名称: {}", parkingStatus.getServiceName());
            log.info("  健康状态: {}", parkingStatus.isHealthy());
            log.info("  最后检查时间: {}", parkingStatus.getLastCheckTime());
            log.info("  连续失败次数: {}", parkingStatus.getConsecutiveFailures());
            
            // 验证基本字段不为空
            if (parkingStatus.getServiceName() != null && 
                parkingStatus.getLastCheckTime() > 0) {
                log.info("✅ 停车服务健康状态验证通过");
            } else {
                log.error("❌ 停车服务健康状态验证失败");
            }
        } else {
            log.warn("未找到停车服务健康状态信息");
        }
        
        log.info("健康检查结果验证完成，总服务数: {}", healthStatusMap.size());
    }
    
    /**
     * 清理测试数据
     */
    public static void cleanupTestData() {
        log.info("清理测试数据...");
        
        // 清理调用统计
        FeignCallMonitorAspect.clearAllCallStatistics();
        
        log.info("测试数据清理完成");
    }
}
